package com.cellulam.framework.core.shortlink;

import com.cellulam.framework.core.utils.JacksonUtils;
import com.cellulam.framework.core.rest.RestClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

@Slf4j
public class ShortLinkGenerator {

    private HttpHeaders httpHeaders;

    private RestClient restClient;

    private final String apiUrl;

    public ShortLinkGenerator(String apiUrl, String token, RestClient restClient) {
        this.restClient = restClient;
        this.apiUrl = apiUrl;

        this.httpHeaders = new HttpHeaders();
        this.httpHeaders.add("token", token);
    }

    public String generate(String url) {
        try {
            ShortLinkResponse response = this.restClient.postForObject(apiUrl,
                    new HttpEntity<>(
                            ShortLinkRequest.builder()
                                    .url(url)
                                    .termOfValidity("long-term")
                                    .build(), httpHeaders
                    ),
                    ShortLinkResponse.class
            );

            if (response.getCode() == 0) {
                return response.getShortUrl();
            }

            log.error("生成短链失败, url: {}, result: {}",
                    url,
                    JacksonUtils.toJson(response));
        } catch (Exception e) {
            log.error("生成短链失败, url: {}",
                    url,
                    e);
        }

        return url;
    }
}
